package me.ahoukuse.koala.service.impl;

import com.alibaba.fastjson2.JSONObject;
import me.ahoukuse.koala.service.CaptchaService;
import me.ahoukuse.koala.util.FileUtil;
import me.ahoukuse.koala.util.MessageUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class CaptchaServiceImpl implements CaptchaService {

    private int titleWidth = 40;
    private int titleHeight = 40;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public JSONObject genCaptcha() throws IOException {
        String id = String.valueOf(UUID.randomUUID());
        ResourceLoader resourceLoader = new DefaultResourceLoader();
        Random random = new Random();
        int capInt = random.nextInt(3);
        Resource resource = resourceLoader.getResource("classpath:" + File.separator + "captcha" + File.separator + "captcha" + capInt + ".png");
        BufferedImage image = ImageIO.read(resource.getInputStream());
        int x = random.nextInt(300 - titleWidth);
        int y = random.nextInt(225- titleHeight);
        int x2 = random.nextInt(60) + 50;
        x2 = x + x2 > 300 - titleWidth ? x - x2 : x + x2;
        BufferedImage subImage;
        if (random.nextBoolean()) {
            subImage = image.getSubimage(x, y, titleWidth, titleHeight);
            redisTemplate.opsForValue().set("captcha:"+id, x, 120, TimeUnit.SECONDS);
        } else {
            subImage = image.getSubimage(x2, y, titleWidth, titleHeight);
            redisTemplate.opsForValue().set("captcha:"+id, x2, 120, TimeUnit.SECONDS);
        }
        String baseSubImage = FileUtil.encodeImageToBase64(subImage);
        Graphics2D g2d = image.createGraphics();
        g2d.setColor(Color.WHITE);
        g2d.fillRect(x , y, 40, 40);
        g2d.fillRect(x2 , y, 40, 40);

        g2d.dispose();
        JSONObject res = MessageUtil.msg(200, "success");
        JSONObject cap = new JSONObject();
        cap.put("img", FileUtil.encodeImageToBase64(image));
        cap.put("puzzle", baseSubImage);
        cap.put("puzzleY", y);
        cap.put("id", id);
        res.put("data",cap);
        return res;
    }
}
